package com.org.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.org.common.PageBean;
import com.org.common.Result;
import com.org.pojo.*;
import com.org.service.ISkillService;
import com.org.service.ServeService;
import com.org.utils.MapUtil;
import com.org.utils.MatchUtil;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * ClassName: ServeController
 * Package: com.org.controller
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/6 13:51
 * @Version 1.0
 */
@RestController
@RequestMapping("/serve")
@CrossOrigin//支持跨域
public class ServeController {

    @Autowired
    private ServeService serveService;

    @Autowired
    private ISkillService skillService;

    @PostMapping("/add")
    public Result add(@RequestBody Serve serve) {
        serveService.add(serve);
        return Result.success();
    }


    @GetMapping("/allList")
    public Result<PageBean<Serve>> allList(
            Integer pageNum,    //第几页
            Integer pageSize,   //页面容量
            String location,    // 老人当前的定位信息（经纬度）
            @RequestParam(required = false) String title,    //非必须
            @RequestParam(required = false) String content,    //非必须
            @RequestParam(required = false) String userType,    //非必须
            @RequestParam(required = false) String createId,    //非必须
            @RequestParam(required = false) String communityId,    //非必须
            @RequestParam(required = false) String duration,    //非必须
            @RequestParam(required = false) String type,    //非必须
            @RequestParam(required = false) String state,    //非必须
            @RequestParam(required = false) String removeDraftAndPending,    //只要不为空，就不显示草稿和待审核
            @RequestParam(required = false) String sortMethod  // 排序方式 可为空
    ) {
        PageBean<Serve> pb = serveService.allList(
                pageNum,
                pageSize,
                location,
                title,
                content,
                type,
                userType,
                createId,
                communityId,
                duration,
                state,
                removeDraftAndPending,
                sortMethod
        );

        return Result.success(pb);
    }

    @GetMapping("/delete")
    public Result<Serve> delete(Integer id) {
        serveService.delete(id);
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<Serve> detail(Integer id, String location) {
        Serve s = serveService.findById(id);
        s.setDistance(MapUtil.getDistance(s.getLocation(), location));
        return Result.success(s);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Serve serve) {
        Serve s = serveService.findById(serve.getId());
        System.out.println(s.getState());
//        if (!s.getState().equals("草稿") && !s.getState().equals("未通过")) {
//            return Result.error("非草稿以及未通过状态不能修改服务内容，请撤销发布后进行修改！");
//        }
        serveService.update(serve);
        return Result.success();
    }

    @GetMapping("/updateState")
    public Result updateState(Integer id, String state) {
        serveService.updateState(id, state);
        return Result.success();
    }

    //@Scheduled(fixedRate = 59000)  // 每59秒执行一次
    @PostMapping("/refresh")
    public Result refresh() {
        serveService.refresh();
        return Result.success();
    }

//    //统计自己已发布
//    @GetMapping("/count")
//    public Result<Integer> count(String title) {
//        Integer num = serveService.count(title);
//        return Result.success(num);
//    }

    /**
     * 老人发布志愿后与技能匹配
     *
     * @param serviceId 服务的id
     * @param location  用户的定位 格式举例： "103.929367,30.742149"
     * @return 如果最后三个都为false的话，则综合考虑进行匹配，
     * 如果最后三个参数某个参数为true的话，则匹配结果优先满足该选项（三个中只能选一个为true）
     */
    @GetMapping("/match")
    public Result<List<Skill>> serviceMatchSkill(
            long serviceId,
            String location, // 老人当前的定位信息（经纬度）
            boolean distanceFirst, // 优先匹配距离最近的
            boolean typeFirst, // 优先匹配服务类型相同的
            boolean timeFirst // 优先匹配服务时间段最贴切的
    ) {
        // 当前服务
        Serve serve = serveService.getById(serviceId);
        // 服务信息
        String serveType = serve.getType();
        LocalDateTime serveStartTime = serve.getStartTime();
        LocalDateTime serveEndTime = serve.getEndTime();

        // 获取技能列表
        List<Skill> skills = skillService.list(new LambdaQueryWrapper<Skill>()
                .eq(Skill::getState, "空闲")
        );

        // 距离优先
        if (distanceFirst) {
            // 更新距离
            for (Skill skill : skills) {
                double dis = MapUtil.getDistance(location, skill.getLocation());
                skill.setDistance(dis);
            }
            // 排序
            skills.sort((o1, o2) -> Double.compare(o1.getDistance(), o2.getDistance()));
            return Result.success(skills);
        }

        // 类型优先
        if (typeFirst) {
            List<Skill> result = new ArrayList<>();
            for (Skill skill : skills) {
                List<String> skillTypes = Arrays.asList(skill.getLable01(), skill.getLable02(), skill.getLable03(), skill.getLable04());
                if (skillTypes.contains(serveType)) {
                    result.add(skill);
                }
            }
            return Result.success(MapUtil.setSkillDistances(result, location));
        }

        // 时间段优先
        if (timeFirst) {
            List<Skill> result = new ArrayList<>();
            for (Skill skill : skills) {
                if (serveStartTime.isAfter(skill.getStarttime()) && serveEndTime.isBefore(skill.getEndtime())) {
                    result.add(skill);
                }
            }
            return Result.success(MapUtil.setSkillDistances(result, location));
        }

        // 按综合分数匹配
        MapUtil.setSkillDistances(skills, location);
        for (Skill skill : skills) {
            double ratio = 1 - skill.getDistance() / 2000 < 0 ? 0 : 1 - skill.getDistance() / 2000;
            double disScore = 30 * ratio;
            skill.setScore(MatchUtil.getScore(skill, serve) + disScore);
        }
        // 排序
        skills.sort((o1, o2) -> Double.compare(o2.getScore(), o1.getScore()));
        return Result.success(skills);
    }

    // 查看自己发布了的服务的数量
    @GetMapping("/count")
    public Result count(){
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");
        Long count = serveService.count(new LambdaQueryWrapper<Serve>().eq(Serve::getCreateId, userId));
        return Result.success(count);
    }
}
